/*
 * @Author: sunzhijun
 * @LastEditors: sunzhijun
 * @Date: 2019-03-23 14:43:10
 * @LastEditTime: 2019-03-24 20:14:11
 */
import React, {Component, PureComponent} from 'react';
import ReactDOM from 'react-dom';
import {high, createPage, base, getUrlParam, toast, promptBox, cacheTools} from 'nc-lightapp-front';
import {hrAjax as ajax, saveValidate, getAppPageConfig} from 'src/hrpub/common/utils/utils';
import handdleCheckedData from '../container/functions/checkDataPermissionAction';
import Header from '../components/Header';
import Pagination from '../components/Pagination';
import SignModal from '../components/SignModal';
import EmptyData from "src/hrpub/common/components/emptyImg";
// import {fixedCol} from "../../../../../hrpub/common/utils/utils";
import {chectFormAction, setFormAttrAndValue} from '../../../../public/functions/checkFormAction';
import setAllpks from '../../../../public/functions/setAllpks';
import IsMac from '../../../../public/functions/isMac';
import './index.less';

const {NCButton, NCSelect, NCCheckbox} = base;
const NCOption = NCSelect.NCOption;
import NCUploader from 'uap/common/components/NCUploader';
import WpsModal from 'src/hrpub/common/components/wpsPreModel';

let tableid = 'dataList';
let cardId = 'dataCard';
const languageId = "sign6011";
const domainName = "hrcm";

class CMSign extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.form('dataCard', 'dataCard_add', 'postcontCard_add', 'secrerycontCard_add', 'traincontCard_add')
            props.use.editTable('dataList', 'psnList', 'postcontList', 'secrerycontList', 'traincontList')
            props.use && props.use.search('listquery', 'query')
        }
        this.config = getAppPageConfig();
        this.state = {
            json: {},
            showMode: 'browse',
            showUploader: false, //是否显示附件管理
            isDataListPage: true, //是否是列表数据页面
            rowsListData: [],  //展示区域数据 
            rowsCardData: [],
            pageType: tableid,
            pageInfo: {
                pageIndex: 1,
                pageSize: 10
            },
            conditions: null,
            nodeRefs: {
                wpsview: null
            }
        }

        this.saveTableData = this.saveTableData.bind(this);
        this.onHideUploader = this.onHideUploader.bind(this);
        this.takeEffectEvent = this.takeEffectEvent.bind(this);
        this.refreshTableData = this.refreshTableData.bind(this);
    }

    componentWillMount() {
        // window.location.hash = `?page=201908221110`;
        let callback = (json, status, inlt) => {
            if (status) {
                this.lang = json
                this.setState({json, inlt}, () => {
                    this.props.createUIDom(this.config, (data) => {
                        let oid = data.template.listquery.oid;
                        let buttons = data.button;
                        //let dataItems = data.template.dataList.items;
                        // let callback = (json, status, inlt) => {
                        //     if (status) {
                        //         this.lang = json
                        //         this.setState({json, inlt},()=>{
                        //             this.initMeta(dataItems,this);
                        //         })//存json和inlt到页面state中并刷新页面
                        //     }
                        // }
                        // this.props.MultiInit.getMultiLang({moduleId: languageId, domainName: domainName, callback});
                        // this.props.meta.setMeta(data && data.template ? data.template : {},()=>{});
                        // this.props.button.setButtons(data && data.button ? data.button : {});
                        this.initMeta(data.template, buttons, this);
                        this.setState({
                            buttons: buttons || [],
                            context: data.context || {},
                            telName: data.template.name || '',
                            oid: oid,
                            pageid: data.template.pageid
                        });
                        this.props.meta.setMeta(data && data.template ? data.template : {}, () => {
                        });
                        this.props.button.setButtons(data && buttons ? buttons : {});
                    });
                })//存json和inlt到页面state中并刷新页面

            }
        }
        this.props.MultiInit.getMultiLang({moduleId: languageId, domainName: domainName, callback})
    }

    componentDidMount() {
        this.updateButtonStatus();
        // 计算列表的高度
        let bodyH = this.refs.getContainerDom.offsetHeight;
        let headerH = this.header.getHeaderH();
        this.setState({
            tableHeight: bodyH - headerH - 44
        })
        this.props.button.setButtonVisible(['newAdd', 'edit', 'delete', 'takeEffect', 'refresh', 'save1', 'cancel1', 'edit', 'text', 'file', 'query'], false);
    }

    //初始化meta数据
    initMeta(template, buttons, opt) {
        let {json} = this.state;
        let data = template.dataList.items;
        // fixedCol(template['dataList'], ['contractnum', 'pk_majorcorp','pk_psndoc.code','pk_psndoc'],json['hrcm-000039'])
        data.unshift({
            attrcode: 'index',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000039'], // 序号
            width: '65px',
            textAlign: 'center',
            visible: true,
            fixed: 'left',
            render(text, record, index) {
                return (
                    <span>{index + 1}</span>
                )
            }
        });
        // 添加超链接和锁定列
        data.forEach((item, key) => {  //添加超链接
            switch (item.attrcode) {
                case 'contractnum':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.render = (text, record, index) => {
                        return (
                            <span className="list-style" style={{color: '#0073E1', cursor: 'pointer'}}
                                  onClick={this.toCardForm.bind(this, record, index, this.props)}>
                                {record && record.values['contractnum'] && record.values['contractnum'].value}
                            </span>
                        );
                    };
                    break;
                case 'pk_majorcorp':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.render = (text, record, index) => {
                        return (
                            <span className="list-style">
                                {record && record.values['pk_majorcorp'] && record.values['pk_majorcorp'].display}
                            </span>
                        );
                    };
                    break;
                case 'pk_psndoc.code':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.render = (text, record, index) => {
                        return (
                            <span className="list-style">
                                {record && record.values['pk_psndoc.code'] && record.values['pk_psndoc.code'].value}
                            </span>
                        );
                    };
                    break;
                case 'pk_psndoc.name':
                    item.renderStatus = 'browse'
                    item.fixed = 'left'
                    item.render = (text, record, index) => {
                        return (
                            <span className="list-style">
                                {record && record.values['pk_psndoc.name'] && record.values['pk_psndoc.name'].value}
                            </span>
                        );
                    };
                    break;
                default:
                    break;
            }
        });
        //添加附件
        data.push({
            attrcode: 'attachment',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000011'], /* 国际化处理： 附件管理*/
            width: '80px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                // let billId = record.values.pk_psndoc_sub.value;
                // let billNo = record.values.contractnum.value
                return (
                    <span>
                        <i className="icon iconfont icon-fujianshenpi" onClick={(eve) => opt.attachManage(record)}></i>
                    </span>
                )
            }
        });
        data.push({
            attrcode: 'handleArea',
            itemtype: 'customer',
            hyperlinkflag: false,
            label: json['hrcm-000012'], /* 国际化处理： 操作*/
            width: '250px',
            textAlign: 'center',
            visible: true,
            fixed: 'right',
            render(text, record, index) {
                let billId = record.values.pk_psndoc_sub.value;
                let billNo = record.values.contractnum.value;
                return buttons && buttons.map((item, index) => {
                    if (item.key === 'edit') {
                        return (
                            <React.Fragment>
                                <span style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                      onClick={opt.modifyCheckData.bind(opt, record)}
                                >
                                    {json['hrcm-000013']}
                                </span>
                            </React.Fragment>
                        )
                    } else if (item.key === 'delete') {
                        return (
                            <React.Fragment>
                                <span style={{color: '#0073E1', cursor: 'pointer', marginRight: '12px'}}
                                      onClick={opt.deleteBatchesData.bind(opt, record)}
                                >
                                    {json['hrcm-000014']}
                                </span>
                            </React.Fragment>
                        )
                    } else if (item.key === 'text') {
                        return (
                            <React.Fragment>
                                <span style={{color: '#0073E1', cursor: 'pointer'}}
                                      onClick={opt.contractText.bind(opt, billId, record)}
                                >
                                    {json['hrcm-000015']}
                                </span>
                            </React.Fragment>
                        )
                    }
                })
            }
        });
    }

    //查询设置组织pkorg
    searchOrganizationChange(data) {
        let pkorg = data.refpk;
        this.setState({
            pk_org: pkorg,
            storageOrgData: data
        }, () => {
            this.getStorageData();
            // this.fetchTableData();
        })
    }

    //根据获取本地存储的主键信息获取数据
    getStorageData() {
        let storage = JSON.parse(window.localStorage.getItem('pageQueryParam'));
        let storageData = storage && Object.keys(storage);
        if (storageData && !!storageData.length) {
            let storage_pk = storage && storage.sign && storage.sign.pk_psndoc_subs;
            let hrorgobj = storage && storage.sign && storage.sign.hrorgobj;
            hrorgobj && this.setState({
                pk_org: hrorgobj.refpk,
                storage_pk: storage_pk
            }, () => {
                this.fetchTableData({key: storage_pk, queryType: 1});
                this.header.setOrganizationValue(hrorgobj);
            })
        } else {
            this.fetchTableData();
        }
    }

    //存储人力资源组织信息
    storageOrgData() {
        let {storageOrgData} = this.state;
        let orgData = {
            sign: {
                hrorgobj: storageOrgData
            }
        }
        orgData && window.localStorage.setItem('pageQueryParam', JSON.stringify(orgData));
    }

    //主键信息格式化
    formatPkPsndocSub(key, areaCode, type) {
        if (key && key.jobpks) {
            if (areaCode != tableid) {
                let len = key.jobpks.length;
                key = key.jobpks[len - 1];
            } else {
                key = [];
            }
        }
        if (key && Object.prototype.toString.call(key) === '[Object Object]') {
            key = [key];
        } else if (Array.isArray(key) && key.length === 0) {
            key = []
        } else if (key) {
            key = [key];
        } else {
            key = []
        }
        if (type == 1 && areaCode == tableid) {
            key = []
        }
        return key;
    }

    //数据初始化
    fetchTableData({key, type, isRefresh, conditions, queryType = 0, isEdit} = {}) {
        let {pk_org, isDataListPage, pageInfo, json, oid} = this.state;
        let areaCode = isDataListPage ? tableid : cardId;
        let pkPsndocSub = this.formatPkPsndocSub(key, areaCode, type);
        let pkPsndocSubArr = []
        pkPsndocSub.forEach((items) => {
            if (Array.isArray(items)) {
                pkPsndocSubArr.push(...items)
            } else {
                pkPsndocSubArr = pkPsndocSub
            }
        })
        if (!!pk_org) {
            ajax({
                url: '/nccloud/hrcm/common/QueryDataAction.do',
                data: {
                    pk_org: pk_org,
                    areaCode: areaCode,
                    queryType: queryType,
                    showSealDataFlag: true,
                    orgFilter: true,
                    isNodeCodeFilter: true,
                    pkPsndocSub: pkPsndocSubArr,      //卡片状态刷新数据
                    pageInfo: pageInfo,
                    appCode: this.config.appcode,
                    ...conditions
                },
                success: res => {
                    if (res.success && res.data) {
                        let data = res.data;
                        let rowsData, allpks;
                        if (isDataListPage) {
                            allpks = data.dataList && data.dataList.allpks || [];
                            rowsData = data && data.dataList.rows;
                            // if(!!rowsData){
                            this.props.button.setButtonVisible(['newAdd', 'delete', 'refresh', 'takeEffect', 'query'], true);
                            this.props.button.setButtonVisible(['save1', 'cancel1', 'text', 'file', 'edit'], false);
                            this.props.button.setButtonDisabled(['edit', 'delete', 'refresh', 'takeEffect', 'file'], false);
                            // }
                            this.props.button.setButtonDisabled(['newAdd'], false);
                            this.props.editTable.setTableData(tableid, {rows: rowsData || []});
                            //设置翻页数据
                            this.setState({
                                pageInfo: res.data.dataList.pageInfo,
                                isVisiblePagination: true   //控制翻页显示隐藏
                            })
                            cacheTools.set('allpks', allpks);
                        } else {
                            rowsData = res.data && res.data.dataCard.rows[0];
                            if (!!rowsData.values.ifprop.value || rowsData.values.ifprop.value === 'Y') {
                                rowsData.values.ifprop.display = json['hrcm-000018'];
                                rowsData.values.ifprop.value = true;
                            } else {
                                rowsData.values.ifprop.display = json['hrcm-000019'];
                                rowsData.values.ifprop.value = false;
                            }
                            if (!!rowsData) {
                                let formData = {
                                    rows: new Array(rowsData)
                                };
                                this.props.form.setAllFormValue({[cardId]: formData});
                            }
                            if (!!key.jobpks || Array.isArray(key)) { //数组是新增过来的数据
                                allpks = cacheTools.get('allpks');
                                if (!!key.jobpks) {
                                    key = key.jobpks;
                                }
                                let newAllpks = allpks.concat(key);
                                let len = key.length;
                                newAllpks = Array.from(new Set(newAllpks));
                                cacheTools.set('allpks', newAllpks);
                                this.header.setCardPagination(key[len - 1]);
                            } else if (!!key) {      //字符串是删除生效时的数据
                                this.header.setCardPagination(key);
                            }
                            this.hidePagination();
                        }
                        if(isEdit){
                            rowsData = res.data && res.data.dataCard.rows[0];
                            if (rowsData && rowsData.values.ifprop.value === 'Y' || rowsData && rowsData.values.ifprop.value === true) {
                                this.props.form.setFormItemsValue(cardId, {'ifprop': {display: json['hrcm-000018'], value: true, scale: "-1"}})
                            } else {
                                this.props.form.setFormItemsValue(cardId, {'ifprop': {display: json['hrcm-000019'], value: false, scale: "-1"}});
                                // form.setFormItemsDisabled(cardId, { 'promonth': true, 'prop_unit': true, 'probegindate': true, 'probenddate': true });
                            }
                            this.editCardData(rowsData);
                        }
                    } else {
                        // this.props.button.setButtonVisible(['newAdd','delete','takeEffect', 'refresh'],true);
                        // this.props.button.setButtonVisible(['save1','cancel1','text','file'],false);
                        this.props.button.setButtonVisible({
                            save1: false,
                            cancel1: false,
                            text: false,
                            file: false,
                            newAdd: true,
                            delete: true,
                            takeEffect: true,
                            refresh: true
                        })
                        this.props.button.setButtonDisabled({
                            edit: true,
                            delete: true,
                            takeEffect: true,
                            refresh: true,
                            newAdd: false
                        })
                        // this.props.button.setButtonDisabled(['edit','delete','takeEffect','refresh'],true);
                        // this.props.button.setButtonDisabled(['newAdd'],false);
                        this.props.editTable.setTableData(tableid, {rows: []});
                        this.props.form.EmptyAllFormValue(cardId);
                        this.hidePagination();
                        if (isDataListPage) {
                            this.props.button.setButtonDisabled(['refresh'], false);
                            this.props.button.setButtonVisible(['query'], true);
                        } else {
                            this.props.button.setButtonDisabled(['refresh'], true);
                            this.props.button.setButtonVisible(['query'], false);
                        }
                    }
                    if (!!isRefresh) {
                        toast({color: 'success', content: json['hrcm-000016']});
                    }
                    this.deleteStorage();
                }
            })
        } else {
            // this.props.button.setButtonDisabled(['newAdd','edit','delete','takeEffect','file'],true);
            this.props.button.setButtonVisible(['newAdd', 'edit', 'delete', 'takeEffect', 'refresh', 'query'], false);
            this.hidePagination();
        }
    }

    //删除localStorage
    deleteStorage() {
        let pageQueryParamObj = JSON.parse(localStorage.getItem('pageQueryParam'));
        if (!!pageQueryParamObj) {
            delete pageQueryParamObj.sign;
            localStorage.setItem('pageQueryParam', JSON.stringify(pageQueryParamObj));
        }
    }

    //列表
    getTableListData() {
        let {pk_org, json} = this.state;
        let tableHeight = this.state.tableHeight;
        if (!!pk_org) {
            return (
                <div className="nc-singleTable-table-area nc-bill-table-area">
                    {this.props.editTable.createEditTable(tableid, {
                        cancelCustomRightMenu: true,
                        //showIndex: true, 		//显示序列号
                        showCheck: true,        //显示复选框
                        onRowDoubleClick: this.toCardForm.bind(this),    //编辑表格数据
                        sort: {
                            mode: 'single', backSource: false, sortFun: (v, rows) => {
                                setAllpks(rows, 'pk_psndoc_sub')
                            }
                        },
                        // onSelected: this.getSelectedData.bind(this),     //获取选中的数据
                        height: tableHeight - 72    //设置高度
                    })}
                </div>
            )
        } else {
            return (
                <EmptyData text={json['hrcm-000017']}></EmptyData>
            )
        }
    }

    //隐藏列表翻页
    hidePagination() {
        this.setState({
            isVisiblePagination: false   //控制翻页显示隐藏
        })
    }

    //保存
    saveTableData(step) {
        let formData = this.props.form.getAllFormValue(cardId).rows;
        let stepNum = step ? step : '0';
        let {json, pageid} = this.state;
        saveValidate(this.props, pageid, cardId, null, 'form').then(() => {
            if (this.props.form.isCheckNow(cardId)) {
                ajax({
                    url: '/nccloud/hrcm/make/UpdateSaveDataAction.do',
                    data: {
                        baseParam: {
                            step: stepNum
                        },
                        formData: {
                            model: {
                                rows: formData
                            }
                        }
                    },
                    success: res => {
                        if (res.success && res.data) {
                            let data = res.data;
                            let content = {
                                content: data.msg
                            }
                            if (data.step == '1') {
                                let fn = {
                                    sureFn: this.saveTableData.bind(this)
                                }
                                this.promptBoxModal(content, fn, '1');
                            } else if (data.step == '3') {
                                let fn = {
                                    sureFn: this.isTakeEffectEvent.bind(this)
                                }
                                content.sureName = json['hrcm-000018'];
                                content.cancelName = json['hrcm-000019'];
                                this.refreshTableData();
                                this.updateShowMode('browse');
                                this.promptBoxModal(content, fn, '3');
                            } else {
                                this.refreshTableData();
                            }
                        }
                    }
                })
            }
        });
    }

    //操作卡片翻页
    handleCardPagination(pks) {
        this.fetchTableData({key: pks});
    }

    //确认弹窗
    promptBoxModal(context, fn = {}, args) { //context 内容；fn 执行的方法；args 传递的参数
        let {sureFn, cancelFn} = fn;
        let {json} = this.state;
        promptBox({
            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: json['hrcm-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
            content: context.content,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
            beSureBtnName: context.sureName ? context.sureName : json['hrcm-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
            cancelBtnName: context.cancelName ? context.cancelName : json['hrcm-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
            hasCloseBtn: true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
            // beSureBtnClick: ()=>{ this.resetTableData() },   // 确定按钮点击调用函数,非必输
            beSureBtnClick: () => {
                sureFn && sureFn(args)
            },   // 确定按钮点击调用函数,非必输
            cancelBtnClick: () => {
                cancelFn && cancelFn(args)
            },  // 取消按钮点击调用函数,非必输
            // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
            closeByClickBackDrop: false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
        })
    }

    //刷新
    refreshTableData(isRefresh) {
        this.setState({
            isDataListPage: !this.state.isDataListPage ? false : true,
            storage_pk: []
        }, () => {
            if (this.state.isDataListPage) {
                this.fetchTableData({isRefresh: isRefresh});
            } else {
                let pk_psndoc_sub = this.props.form.getAllFormValue(cardId).rows[0].values.pk_psndoc_sub.value;
                this.fetchTableData({key: pk_psndoc_sub, isRefresh: isRefresh});
            }
        })

    }

    //获取某一处修改的数据索引
    searchIndex(arr, id) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].rowid == id) {
                return i;
            }
        }
    }

    // 按钮是否显示，按钮是否可用
    updateButtonStatus() {
        var showMode = this.state.showMode
        this.props.button.setButtonsVisible({
            newAdd: showMode === 'browse',
            edit: showMode === 'browse',
            delete: showMode === 'browse',
            text: showMode === 'browse',
            refresh: showMode === 'browse',
            takeEffect: showMode === 'browse',
            file: showMode === 'browse',
            save1: showMode === 'edit',
            cancel1: showMode === 'edit'
        })
    }

    // 更新界面状态
    updateShowMode(showMode) {
        // var oldMode = this.state.showMode;
        let {json} = this.state;
        this.setState({
            showMode: showMode
        }, () => {
            this.updateButtonStatus()
        })
        if ('edit' === showMode) {
            this.props.form.setFormStatus(cardId, 'edit');
        } else {
            // this.props.editTable.cancelEdit(tableid);
            this.props.form.cancel(cardId);
            this.header.setCardPaginationVisibleFn(true);
            let formData = this.props.form.getAllFormValue(cardId);
            if (formData && formData.rows[0].values.ifprop && formData.rows[0].values.ifprop.value === 'Y' || formData.rows[0].values.ifprop && formData.rows[0].values.ifprop.value === true) {
                this.props.form.setFormItemsValue(cardId, {
                    'ifprop': {
                        display: json['hrcm-000018'],
                        value: true,
                        scale: "-1"
                    }
                })
            } else {
                this.props.form.setFormItemsValue(cardId, {
                    'ifprop': {
                        display: json['hrcm-000019'],
                        value: false,
                        scale: "-1"
                    }
                })
            }
            // this.props.form.setFormStatus(cardId,'browse');
        }
    }

    //返回
    handleBackClick() {
        let {storage_pk} = this.state;
        this.setState({
            isDataListPage: true
        }, () => {
            this.props.button.setButtonVisible(['newAdd', 'delete', 'refresh', 'takeEffect', 'query'], true);
            this.props.button.setButtonVisible(['save1', 'cancel1', 'text', 'file', 'edit'], false);
            this.fetchTableData({key: storage_pk});
        })
    }

    //进入卡片态调用接口
    // getCardData(pk, type) {
    //     const { form, button } = this.props;
    //     let { pk_org, json } = this.state;
    //     ajax({
    //         url: '/nccloud/hrcm/common/QueryDataCardAction.do',
    //         data: {
    //             pk_psndoc_sub: pk,
    //             areaCode: cardId,
    //             pk_org: pk_org
    //         },
    //         success: (res) => {
    //             let data = res.data;
    //             if (data && data.data) {
    //                 let formData = data.data.dataCard;
    //                 form.setAllFormValue({ [cardId]: formData });
    //                 button.setButtonVisible(['file', 'edit', 'text'], true);
    //                 // setFormAttrAndValue(data.attrMap, data.valueMap, this.props, cardId, [cardId]);
    //                 if (type === 'edit') {
    //                     this.editCardData(formData);
    //                 }
    //                 if (formData && formData.rows[0].values.ifprop.value === 'Y' || formData && formData.rows[0].values.ifprop.value === true) {
    //                     form.setFormItemsValue(cardId, { 'ifprop': { display: json['hrcm-000018'], value: "Y", scale: "-1" } })
    //                 } else {
    //                     form.setFormItemsValue(cardId, { 'ifprop': { display: json['hrcm-000019'], value: "N", scale: "-1" } });
    //                     form.setFormItemsDisabled(cardId, { 'promonth': true, 'prop_unit': true, 'probegindate': true, 'probenddate': true });
    //                 }
    //             }
    //         }
    //     })
    // }

    //进入CardForm
    toCardForm(records) {
        this.setState({
            isDataListPage: false,
            isVisiblePagination: false //控制翻页显示隐藏
        }, () => {
            let pk_psndoc_sub = records.values.pk_psndoc_sub.value;
            // this.getCardData(pk_psndoc_sub);
            this.editTableFn(records);
            // this.getCardFormData(pk_psndoc_sub);
            this.header.showHeadLeftFn(true, pk_psndoc_sub);
            this.header.getCardFormId(cardId);
        })
    }

    //进入CardForm展示数据
    editTableFn(records) {
        let props = this.props;
        let {json} = this.state;
        let pk_psndoc_sub = records.values.pk_psndoc_sub.value;
        // this.getCardFormData(pk_psndoc_sub);
        /*let rowsData;
        if(records){
            rowsData = records;
        }else{
            rowsData = this.props.editTable.getCheckedRows(tableid)[0].data;
        }
        let formData = {
            rows: new Array(rowsData)
        };
        this.props.form.setAllFormValue({[cardId]: formData});*/
        this.fetchTableData({
            key: pk_psndoc_sub,
            isRefresh: false
        })
        this.props.button.setButtonVisible(['file', 'edit', 'text'], true);
        this.props.button.setButtonVisible(['query'], false);
        /*if(formData && formData.rows[0].values.ifprop.value === true){
            this.props.form.setFormItemsValue(cardId,{'ifprop':{display: json['hrcm-000018'], value: true, scale: "-1"}})
        }else{
            this.props.form.setFormItemsValue(cardId,{'ifprop':{display: json['hrcm-000019'], value: false, scale: "-1"}})
        }*/
        // chectFormAction('cont_unit', cardId, props, [cardId]);
    }

    // 修改数据校验事件
    modifyCheckData(v) {
        let {isDataListPage} = this.state;
        let pk_psndoc_sub;
        if (isDataListPage) {
            pk_psndoc_sub = v.values.pk_psndoc_sub.value;
        } else {
            let formCardData = this.props.form.getAllFormValue(cardId);
            pk_psndoc_sub = formCardData && formCardData.rows[0].values.pk_psndoc_sub.value;
        }
        handdleCheckedData(pk_psndoc_sub, 'edit', 'contract', () => {
            if (isDataListPage) {
                this.modifyListData(v);
            } else {
                this.editCardData();
            }
        });
    }

    //修改列表数据
    modifyListData(v) {
        let {form} = this.props;
        let {json} = this.state;
        let formData = v;
        this.setState({
            isDataListPage: false,
            isVisiblePagination: false
        }, () => {
            /*formData = {
                rows: new Array(formData)
            };*/
            let pk_psndoc_sub = formData.values.pk_psndoc_sub.value;
            this.fetchTableData({
                key: pk_psndoc_sub,
                isRefresh: false,
                isEdit: true
            })
            this.header.showHeadLeftFn(true);
            //this.props.form.setAllFormValue({[cardId]: formData});
            /*if (formData && formData.rows[0].values.ifprop.value === 'Y' || formData && formData.rows[0].values.ifprop.value === true) {
                form.setFormItemsValue(cardId, {'ifprop': {display: json['hrcm-000018'], value: true, scale: "-1"}})
            } else {
                form.setFormItemsValue(cardId, {'ifprop': {display: json['hrcm-000019'], value: false, scale: "-1"}});
                // form.setFormItemsDisabled(cardId, { 'promonth': true, 'prop_unit': true, 'probegindate': true, 'probenddate': true });
            }
            this.editCardData(formData);*/
            // let pk_psndoc_sub = v.values.pk_psndoc_sub.value;
            // this.getCardData(pk_psndoc_sub, 'edit');
        });
        // this.props.editTable.getCheckedRows(tableid);
    }

    //编辑卡片时数据
    editCardData() {
        let {json, pk_org} = this.state;
        let extendParam = {
            pk_org: pk_org
        }
        // this.props.form.setFormItemAutoFocus(cardId, 'contractnum');
        this.props.form.setFormStatus(cardId, 'edit');
        this.props.button.setButtonVisible(['newAdd', 'edit', 'delete', 'text', 'refresh', 'takeEffect', 'file', 'query'], false);
        this.props.button.setButtonVisible(['save1', 'cancel1'], true);
        this.header.setCardPaginationVisibleFn(false);
        this.header.getCardFormId(cardId);
        chectFormAction('', cardId, this.props, [cardId], this.config.appcode, extendParam);
    }

    //卡片日期设置
    handleEditFormDate(props, moduleId, key, value) {
        chectFormAction(key, moduleId, props, [cardId]);
    }

    //form编辑前事件
    handleEditBefore(props, moduleId, key, value, data) {
        if (key == 'pk_conttext') {
            let that = this;
            let meta = that.props.meta.getMeta();
            let pk_org = this.state.pk_org;
            meta[moduleId].items.find(item => item.attrcode === key).queryCondition = function () {
                return {
                    "pk_org": pk_org,
                    "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
                }
            };
            that.props.meta.setMeta(meta);
        }
        return true;
    }

    // 点击生效事件
    isTakeEffectEvent(step) {
        let pks = this.getPkPsndocSub();
        !!pks && handdleCheckedData(pks, 'effect', 'contract', () => {
            this.takeEffectEvent(step);
        });
    }

    //获取主键
    getPkPsndocSub() {
        let {isDataListPage, json} = this.state;
        let isCard = isDataListPage ? false : true;
        let pks = [];
        if (isCard) {
            pks = this.props.form.getAllFormValue(cardId).rows[0].values.pk_psndoc_sub.value;
        } else {
            let checkedData = this.props.editTable.getCheckedRows(tableid);
            if (!checkedData.length) {
                toast({color: 'warning', content: json['hrcm-000020']});
                return;
            }
            checkedData.map((v) => {
                pks.push(v.data.values.pk_psndoc_sub.value);
            })
        }
        return pks;
    }

    //是否生效
    takeEffectEvent(step, info) {
        let pageType = '';
        let formData = [];
        let stepNum = step ? step : '0';
        let {isDataListPage, json, storage_pk} = this.state;
        let isCard = isDataListPage ? false : true;
        let pks = this.getPkPsndocSub();
        if (!isCard) {
            pageType = 'list';
        } else {
            pageType = 'card';
        }
        ajax({
            url: '/nccloud/hrcm/make/MakeEffectiveAction.do',
            data: {
                baseParam: {
                    step: stepNum,
                    pageType: pageType,
                    info2: info
                },
                selectCtrtpks: pks
            },
            success: res => {
                if (res.success && res.data) {
                    let data = res.data;
                    let info = res.data.info || null;
                    if (data.step == '99') {
                        if (isCard) {
                            let allpks = cacheTools.get('allpks') || [];
                            let index = 0;
                            let len = allpks.length;
                            len && allpks.forEach((v, i) => {
                                if (v == pks) {
                                    allpks.splice(i, 1);
                                    if (i < len - 1) {
                                        index = i;
                                    } else if (i == len - 1) {
                                        index = i - 1;
                                    }
                                }
                            })
                            cacheTools.set('allpks', allpks);
                            this.fetchTableData({key: allpks[index]});
                        } else {
                            this.fetchTableData({key: storage_pk});
                        }
                    } else {
                        let fn = {
                            sureFn: this.takeEffectEvent
                        }
                        let content = {
                            content: data.msg,
                            sureName: json['hrcm-000018'],
                            cancelName: json['hrcm-000019']
                        }
                        this.promptBoxModal(content, fn, data.step, info);
                    }
                }
            }
        })
    }

    // 关闭附件
    onHideUploader() {
        this.setState({
            showUploader: false
        })
    };

    //批量删除
    deleteBatchesData(v) {
        let pks;
        if (!!v) {
            pks = v && v.values.pk_psndoc_sub.value;
        } else {
            pks = this.getPkPsndocSub();
        }
        !!pks && handdleCheckedData(pks, 'delete', 'contract', () => {
            this.delPrompt(pks)
        });
    }

    // 删除确认弹窗
    delPrompt(delDataPks) {
        let fn = {
            sureFn: () => {
                this.deleteData(delDataPks)
            }
        }
        let content = {
            content: this.state.json['hrcm-000021']
        }
        this.promptBoxModal(content, fn);
    }

    //行删除事件
    // deleteRowData(v){
    //     let pks = v && v.values.pk_psndoc_sub.value;
    //     handdleCheckedData(pks, 'delete', 'contract', ()=>{
    //         this.delPrompt(pks);
    //     });
    // }

    // //是否删除行上数据
    // isDeleteRowData(delDataPks){
    //     let { json } = this.state; 
    //     let fn = {
    //         sureFn: ()=>{ this.deleteData(delDataPks) }
    //     }
    //     let content = {
    //         content: json['hrcm-000021']
    //     }
    //     this.promptBoxModal(content,fn);
    // }

    //删除数据
    deleteData(PKsData) {
        let {storage_pk, isDataListPage, pk_org} = this.state;
        let isCard = isDataListPage ? false : true;
        ajax({
            url: '/nccloud/hrcm/make/MakeDeleteAction.do',
            data: {
                pk_org: pk_org,
                modename: 'hi_psndoc_ctrt', //此处暂时写死
                isCard: isCard,
                allpks: PKsData
            },
            success: res => {
                if (res.success && res.data) {
                    if (isCard) {
                        let allpks = cacheTools.get('allpks') || [];
                        let index = 0;
                        let len = allpks.length;
                        len && allpks.forEach((v, i) => {
                            if (v == PKsData) {
                                allpks.splice(i, 1);
                                if (i < len - 1) {
                                    index = i;
                                } else if (i == len - 1) {
                                    index = i - 1;
                                }
                            }
                        })
                        cacheTools.set('allpks', allpks);
                        if (allpks.length === 0) {
                            this.header.handleBackBtn(() => {
                                this.setState({
                                    isDataListPage: true
                                }, () => {
                                    this.props.button.setButtonVisible(['newAdd', 'delete', 'refresh', 'takeEffect', 'query'], true);
                                    this.props.button.setButtonVisible(['save1', 'cancel1', 'text', 'file', 'edit'], false);
                                    this.fetchTableData({key: allpks[index]});
                                })
                            })
                        } else {
                            this.fetchTableData({key: allpks[index]});
                        }


                    } else {
                        this.fetchTableData({key: storage_pk});
                    }
                }
            }
        })
    }

    //合同文本
    contractText(v, record) {
        let pks = v;
        let json = this.state.json;
        if (IsMac(json['hrcm-000040'])) {
            return false
        }
        ajax({
            url: '/nccloud/hrcm/templet/ContractTextViewAction.do',
            data: {
                pk_org: this.state.pk_org,
                pk_psndoc_subs: pks,
            },
            success: res => {
                if (res.success && !!res.data) {
                    // let protocol = window.location.protocol;
                    // let host = window.location.host;
                    // let openUrl = "uclient://start/" + protocol + "//" + host + res.data;
                    // // let winOpen = window.open('','_self');
                    // top.location.href = openUrl;
                    if (this.state.isDataListPage) {
                        this.state.nodeRefs.wpsview.openView([{data: record}], 'ct')
                    } else {
                        /*获取表单所有数据*/
                        let formData = this.props.form.getAllFormValue(cardId).rows;
                        this.state.nodeRefs.wpsview.openView(formData, 'ct')
                    }
                } else {
                    toast({color: 'warning', content: res.error.message});
                }
            }
        })
    }

    //操作翻页方法
    changePagination(pageInfo) {
        const {conditions} = this.state
        this.setState({
            pageInfo
        }, () => {
            this.fetchTableData({conditions});
        })
    }

    //改变每页展示数据量
    pageSizeSelect(pageInfo) {
        const {conditions} = this.state
        this.setState({
            pageInfo
        }, () => {
            this.fetchTableData({conditions});
        })
    }

    //取消编辑态
    cancelEditStatus() {
        let {json} = this.state;
        let fn1 = {
            sureFn: this.updateShowMode.bind(this)
        }
        let content = {
            content: json['hrcm-000022']
        }
        this.promptBoxModal(content, fn1, 'browse');
    }

    //附件管理
    attachManage(record) {
        let billId, billNo;
        if (!!record) {
            billId = record.values.pk_psndoc_sub.value;
            billNo = record.values.contractnum.value
        } else {
            let cardData = this.props.form.getAllFormValue(cardId).rows[0].values;
            billId = cardData.pk_psndoc_sub.value;
            billNo = cardData.contractnum.value;
        }
        handdleCheckedData(billId, 'attachment', 'contract', () => {
            this.setState({
                showUploader: true,
                billId: billId,
                billNo: billNo
            })
        });
    }

    //打开查询
    listQuery() {
        let {pk_org} = this.state;
        this.props.search.openAdvSearch('listquery', true, () => {
            let meta = this.props.meta.getMeta();
            let items = meta.listquery.items;
            items.length > 0 && items.map((item, index) => {
                if (item.attrcode === 'pk_psnjob.pk_dept') {
                    item.queryCondition = {
                        pk_hrorg: pk_org
                    }
                } else if (item.attrcode === 'pk_conttext') {
                    item.queryCondition = {
                        pk_org: pk_org,
                        GridRefActionExt: 'nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder'
                    }
                }
            })
            this.props.meta.setMeta(meta);
        });
    }

    // 查询数据
    searchData = () => {
        // let conditions = props.search.getAllSearchData('query').conditions || [];
        let getConditions = this.props.search.getQueryInfo('listquery', true);
        let conditions = getConditions;
        this.fetchTableData({conditions: conditions});
        this.setState({
            conditions
        })
    }


    // 统一处理按钮事件
    onBtnOperation(props, btncode) {
        switch (btncode) {
            case 'newAdd':
                this.signNode.showNewIncreased(true)
                break;
            case 'edit':
                this.modifyCheckData();
                break;
            case 'delete':
                this.deleteBatchesData();
                break;
            case 'text':
                let cardData = this.props.form.getAllFormValue(cardId);
                let pk_psndoc_sub = cardData.rows[0].values.pk_psndoc_sub.value;
                this.contractText(pk_psndoc_sub);
                break;
            case 'refresh':
                this.refreshTableData(true);
                break;
            case 'save1':
                this.saveTableData();
                break;
            case 'cancel1':
                this.cancelEditStatus();
                break;
            case 'takeEffect':
                this.isTakeEffectEvent();
                break;
            case 'file':
                this.attachManage();
                break;
            case 'query':
                this.listQuery();
                break;
            default:
                break;
        }
    }

    render() {
        let {button, editTable, cardPagination, search, form} = this.props;
        const {createCardPagination} = cardPagination;
        let {createButtonApp} = button;
        let {createEditTable} = editTable;
        let {NCCreateSearch} = search;
        let {createForm} = form;
        let {
            pageInfo,
            isVisiblePagination,
            isDataListPage,
            rowData,
            pk_org,
            showUploader,
            billId,
            billNo,
            json,
            oid,
            nodeRefs
        } = this.state;
        return (
            <div className="nc-single-table nc-bill-card" ref="getContainerDom">
                <Header
                    {...this.props}
                    ref={node => {
                        this.header = node
                    }}
                    onBtnOperation={this.onBtnOperation.bind(this)}
                    handleBackClick={this.handleBackClick.bind(this)}
                    searchOrganizationChange={this.searchOrganizationChange.bind(this)}
                    handleCardPagination={this.handleCardPagination.bind(this)}
                    cancelEditStatus={this.cancelEditStatus.bind(this)}
                >
                </Header>
                <div className="content">
                    {/* 生成表格 */}
                    {isDataListPage ? this.getTableListData() :
                        <div className="header-cardPagination-area">
                            {createForm(cardId, {
                                useFixedHeader: true,
                                onAfterEvent: this.handleEditFormDate.bind(this),
                                onBeforeEvent: this.handleEditBefore.bind(this)
                                // onBeforeEvent: this.handleEditFormDateBefore.bind(this)
                            })}
                        </div>
                    }
                    {/* 操作翻页 */}
                    <Pagination
                        {...this.props}
                        pageInfo={pageInfo}
                        isVisiblePagination={isVisiblePagination}
                        changePagination={this.changePagination.bind(this)}
                        pageSizeSelect={this.pageSizeSelect.bind(this)}
                    />
                </div>
                <div style={{display: "none"}}>
                    {
                        NCCreateSearch('listquery', {
                            clickSearchBtn: () => {
                                this.searchData()
                            },
                            onlyShowAdvArea: false,
                            showAdvSearchPlanBtn: true,
                            saveSearchPlan: true,
                            oid: oid,
                            onlyShowSuperBtn: true
                        })
                    }
                </div>
                {/* 调用新增组件 */}
                <SignModal
                    {...this.props}
                    pkOrg={pk_org} //组织编码必传
                    ref={node => {
                        this.signNode = node
                    }}
                    appCode={this.config.appcode}
                    nodeType={'sign'}
                    fetchTableData={this.fetchTableData.bind(this)}
                    storageOrgData={this.storageOrgData.bind(this)}
                />
                {/* 附件管理 */}
                {showUploader && <NCUploader
                    uploadTitle={this.state.json["cm6011-000062"] /*多语: 附件管理*/}
                    billId={billId}
                    billNo={billNo}
                    placement={'top'}
                    // getGroupList = {this.getGroupList}
                    onHide={this.onHideUploader} // 关闭功能
                    // beforeUpload={this.beforeUpload}
                />
                }
                <WpsModal
                    {...this.props}
                    onRef={ref => nodeRefs.wpsview = ref}
                    appcode={getAppPageConfig().appcode}
                    pk_org={this.state.storageOrgData}
                />
            </div>
        );
    }
}

export default CMSign;
